<template>
  <div class="relative">
    <!-- 触发器按钮 -->
    <div 
      ref="triggerRef" 
      @click="handleTriggerClick"
      @mouseenter="handleMouseEnter"
      @mouseleave="handleMouseLeave"
      @touchstart="handleTouchStart"
      @touchend="handleTouchEnd"
    >
      <slot name="trigger" />
    </div>

    <!-- 下拉菜单 -->
    <Transition
      enter-active-class="transition ease-out duration-200"
      enter-from-class="opacity-0 scale-95"
      enter-to-class="opacity-100 scale-100"
      leave-active-class="transition ease-in duration-150"
      leave-from-class="opacity-100 scale-100"
      leave-to-class="opacity-0 scale-95"
    >
      <div
        v-if="isOpen"
        ref="dropdownRef"
        class="absolute z-50 bg-background-800 border border-background-600 rounded-lg shadow-lg min-w-48 max-w-[calc(100vw-2rem)]"
        :style="{ 
          marginTop: `${props.offset}px`,
          borderRadius: '8px !important'
        }"
        :class="[
          placement === 'bottom-start' ? 'top-full left-0' : '',
          placement === 'bottom-end' ? 'top-full right-0' : '',
          placement === 'top-start' ? 'bottom-full left-0' : '',
          placement === 'top-end' ? 'bottom-full right-0' : '',
          // 移动端优化：确保下拉菜单不会超出屏幕边界
          'sm:min-w-48 min-w-[calc(100vw-4rem)]'
        ]"
        @mouseenter="handleDropdownMouseEnter"
        @mouseleave="handleDropdownMouseLeave"
      >
        <div class="py-1">
          <slot />
        </div>
      </div>
    </Transition>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'

interface Props {
  placement?: 'bottom-start' | 'bottom-end' | 'top-start' | 'top-end'
  closeOnClick?: boolean
  trigger?: 'click' | 'hover'
  hoverDelay?: number
  offset?: number
}

const props = withDefaults(defineProps<Props>(), {
  placement: 'bottom-start',
  closeOnClick: true,
  trigger: 'click',
  hoverDelay: 200,
  offset: 8
})

const emit = defineEmits<{
  'open': []
  'close': []
}>()

// 响应式状态
const isOpen = ref(false)
const triggerRef = ref<HTMLElement>()
const dropdownRef = ref<HTMLElement>()
const hoverTimeout = ref<number | null>(null)
const touchStartTime = ref<number>(0)

// 处理触发器点击
const handleTriggerClick = () => {
  if (props.trigger === 'click') {
    toggleDropdown()
  }
}

// 处理触摸开始
const handleTouchStart = () => {
  touchStartTime.value = Date.now()
}

// 处理触摸结束
const handleTouchEnd = () => {
  const touchDuration = Date.now() - touchStartTime.value
  // 如果是短触摸（小于500ms），则认为是点击
  if (touchDuration < 500) {
    if (props.trigger === 'click') {
      toggleDropdown()
    }
  }
}

// 处理鼠标进入
const handleMouseEnter = () => {
  if (props.trigger === 'hover') {
    if (hoverTimeout.value) {
      clearTimeout(hoverTimeout.value)
      hoverTimeout.value = null
    }
    openDropdown()
  }
}

// 处理鼠标离开
const handleMouseLeave = () => {
  if (props.trigger === 'hover') {
    hoverTimeout.value = window.setTimeout(() => {
      closeDropdown()
    }, props.hoverDelay)
  }
}

// 处理下拉菜单鼠标进入
const handleDropdownMouseEnter = () => {
  if (props.trigger === 'hover') {
    if (hoverTimeout.value) {
      clearTimeout(hoverTimeout.value)
      hoverTimeout.value = null
    }
  }
}

// 处理下拉菜单鼠标离开
const handleDropdownMouseLeave = () => {
  if (props.trigger === 'hover') {
    hoverTimeout.value = window.setTimeout(() => {
      closeDropdown()
    }, props.hoverDelay)
  }
}

// 切换下拉菜单
const toggleDropdown = () => {
  isOpen.value = !isOpen.value
  
  if (isOpen.value) {
    emit('open')
  } else {
    emit('close')
  }
}

// 打开下拉菜单
const openDropdown = () => {
  isOpen.value = true
  emit('open')
}

// 关闭下拉菜单
const closeDropdown = () => {
  isOpen.value = false
  emit('close')
}

// 点击外部关闭下拉菜单
const handleClickOutside = (event: MouseEvent) => {
  if (triggerRef.value && !triggerRef.value.contains(event.target as Node) &&
      dropdownRef.value && !dropdownRef.value.contains(event.target as Node)) {
    closeDropdown()
  }
}

// 处理菜单项点击
const handleMenuItemClick = () => {
  if (props.closeOnClick) {
    nextTick(() => {
      closeDropdown()
    })
  }
}

// 暴露方法给父组件
defineExpose({
  open: () => {
    isOpen.value = true
    emit('open')
  },
  close: closeDropdown,
  toggle: toggleDropdown
})

// 生命周期
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
  if (hoverTimeout.value) {
    clearTimeout(hoverTimeout.value)
  }
})
</script>
